package com.umpay.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class PropertiesUtil {

    private static final Logger log = LogManager.getLogger(PropertiesUtil.class);

    // 静态对象初始化[在其它对象之前]
    private static Hashtable<String, Object> register = new Hashtable<String, Object>();

    // 不能实例化
    private PropertiesUtil() {
        super();
    }

    /**
     * 读取配置文件
     * 
     * @param java.lang.String
     *            fileName 文件名
     * @return Properties
     */
    public static Properties getProperties(String fileName) {// 传递配置文件路径
        InputStream is = null;// 定义输入流is
        Properties p = null;
        try {
            p = (Properties) register.get(fileName);// 将fileName存于一个HashTable
            /**
             * 如果为空就尝试输入进文件
             */
            if (p == null) {
                fileName = StringUtils.trim(fileName);
                File f = new File(fileName);
                if (f.exists()) {
                    // fileName为绝对路径
                    log.info("通过绝对路径获取配置文件：" + fileName);
                    is = new FileInputStream(f);
                } else {
                    try {
                        is = PropertiesUtil.class.getClassLoader()
                                .getResourceAsStream("param" + File.separator + fileName);
                    } catch (Exception e) {
                        String realPath = Thread.currentThread().getContextClassLoader().getResource("").getPath()
                                + "param" + File.separator + fileName;
                        // String resinHome = System.getProperty("resin.home");
                        // String realPath = null;// 文件的绝对路径
                        // realPath = resinHome + File.separator + "conf/spay/" + fileName;
                        f = new File(realPath);
                        if (f.exists()) {
                            log.info("outsite配置文件的绝对路径：" + realPath);
                            is = new FileInputStream(f);
                        } else {
                            // 用getResourceAsStream()方法用于定位并打开外部文件。
                            String temStr = fileName;
                            if (!fileName.startsWith(File.separator)) {
                                temStr = "/" + temStr;
                            }
                            log.info("通过getResourceAsStream获取配置文件：" + temStr);
                            is = PropertiesUtil.class.getResourceAsStream(temStr);
                        }
                    }

                }

                p = new Properties();
                p.load(is);// 加载输入流
                register.put(fileName, p);// 将其存放于HashTable缓存
                is.close();// 关闭输入流
            }
        } catch (Exception e) {
            log.error(String.format("读取配置文件%s异常：", fileName), e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    log.error("加载配置文件" + fileName + "关闭输入流异常", e);
                }
                is = null;
            }
        }
        return p;// 返回Properties对象
    }

    /**
     * <p>
     * 读取配置文件中的字串属性
     * </p>
     * 
     * @author Ding Zhe, Aug 12, 2013 11:25:59 AM
     * @param fileName
     *            属性文件名
     * @param strKey
     *            Key
     * @return
     */
    public static String getStrValue(String strKey) {
        return getStrValue(strKey, "");
    }

    /**
     * 读取配置文件中的字串属性
     * 
     * @param fileName
     *            属性文件名
     * @param strKey
     *            Key
     * @param defaultValue
     *            缺省值
     */
    public static String getStrValue(String strKey, String defaultValue) {
        Properties p = getProperties("diff.properties");
        try {
            return p.getProperty(strKey, defaultValue);
        } catch (Exception e) {
            log.error("读取配置文件中的字串属性异常，返回默认值：", e);
            return defaultValue;
        }
    }

    /**
     * 读取业务配置文件中的字串属性
     * 
     * @param fileName
     *            属性文件名
     * @param strKey
     *            Key
     * @param defaultValue
     *            缺省值
     */
    public static String getBusiStrValue(String strKey, String defaultValue) {
        Properties p = getProperties("global_params.properties");
        try {
            return p.getProperty(strKey, defaultValue);
        } catch (Exception e) {
            log.error("读取配置文件中的字串属性异常，返回默认值：", e);
            return defaultValue;
        }
    }
    /**
     * 读取业务配置文件中的字串属性
     * 
     * @param fileName
     *            属性文件名
     * @param strKey
     *            Key
     * @param defaultValue
     *            缺省值
     */
    public static String getRetDataValue(String strKey, String defaultValue) {
        Properties p = getProperties("comm_field_convert.properties");
        try {
            return p.getProperty(strKey, defaultValue);
        } catch (Exception e) {
            log.error("读取配置文件中的字串属性异常，返回默认值：", e);
            return defaultValue;
        }
    }
    public static Map<String, String> OrganizationalNotifyDataFromConfigFile(Map<String, Object> resMap,
            String Configkey, String separator) {
        Map<String, String> retMap = new HashMap<String, String>();
        String value = StringUtils.trim(getBusiStrValue(Configkey, ""));
        if (value == null || "".equals(value)) {
            log.error(String.format("[%s]配置内容不存在！", Configkey));
            return null;
        }
        if (!value.contains(separator)) {
            log.error(String.format("[%s]配置内容格式不正确！缺少必要的分割符[%s]", Configkey, separator));
            return null;
        }
        String[] values = value.split(separator);
        for (int i = 0; i < values.length; i++) {
            String key = values[i];
            String merKey = StringUtils.trim(getRetDataValue(key,""));
            if (!StringUtils.isEmpty(StringUtils.trim(resMap.get(key)))) {
                log.info(String.format("【需要通知的字段】%s=%s", key, resMap.get(key)));
                retMap.put(merKey, StringUtils.trim(resMap.get(key)));
            }
        }
        return retMap;
    }
    
    
    /* ********************************************
     * method name   : getPk 
     * description   : 
     * @return       : PrivateKey
     * @param        : @param b
     * @param        : @return
     * modified      : ncc ,  2018年9月18日 下午5:39:44
     * @see          : 
     * ********************************************/      
    public static PrivateKey getPk(byte[] b){
		PKCS8EncodedKeySpec peks = new PKCS8EncodedKeySpec(b);
        KeyFactory kf;
        PrivateKey pk;
		try {
			kf = KeyFactory.getInstance("RSA");
			pk = kf.generatePrivate(peks);
			return pk;
		} catch (NoSuchAlgorithmException e) {
			RuntimeException rex = new RuntimeException();
			rex.setStackTrace(e.getStackTrace());
			throw rex;
		}catch (InvalidKeySpecException e) {
			RuntimeException rex = new RuntimeException();
			rex.setStackTrace(e.getStackTrace());
			throw rex;
		}
	}  


    public static void main(String[] args) {
        String a = "1,2,3";
        String b = "1,2,3,";

        System.out.println(a.split(",").length);

    }
}
